#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Remake of original creole2html.py from Radomir Dopieralski <creole@sheep.art.pl>
Creates DOM nodes in minidom subtree instead of direct writing them to the output.
"""

import re
from creole import Parser
import xml.dom as dom

class Rules:
    # For the link targets:
    proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc'
    extern = r'(?P<extern_addr>(?P<extern_proto>%s):.*)' % proto
    interwiki = r'''
            (?P<inter_wiki> [A-Z][a-zA-Z]+ ) :
            (?P<inter_page> .* )
        '''

class MinidomEmitter:
	"""
	Generate HTML output for the document
	tree consisting of DocNodes.
	"""

	addr_re = re.compile('|'.join([
           Rules.extern,
            Rules.interwiki,
        ]), re.X | re.U) # for addresses
#	addr_re = re.compile(Rules.proto)
	subst = {
		'emphasis':'i',
		'strong':'b',
		'paragraph':'p',
		'bullet_list':'ul',
		'number_list':'ol',
		'list_item':'li',
		'table':'table',
		'table_row':'tr',
		'table_cell':'td',
		'table_head':'th',
		'code':'tt',
		'break':'br',
		'separator':'hr',
		'preformatted':'pre'
		}
	def __init__(self, root, node):
		self.root = root
		self.xml = node.ownerDocument

	def get_text(self, node):
		"""Try to emit whatever text is in the node."""
		try:
			return node.children[0].content or ''
		except:
			return node.content or ''
<<<<<<< .mine
=======

	def html_escape(self, text): return text
	attr_escape = html_escape
>>>>>>> .r154

	# *_emit methods for emitting nodes of the document:

	def document_emit(self, node, xml_node): return self.xml.documentElement

	def text_emit(self, node, xml_node):
		xml_node.appendChild(self.xml.createTextNode(node.content))
		return xml_node
	
	def empty_container(self, node, xml_node):
		"""
		Adds tags around text
		"""
		new_node = self.xml.createElement(self.subst[node.kind])
		xml_node.appendChild(new_node)
		return new_node

	paragraph_emit = bullet_list_emit = number_list_emit = list_item_emit = table_emit = table_row_emit = \
	table_cell_emit = table_head_emit = emphasis_emit = strong_emit = empty_container
	
	def single_tag(self, node, xml_node):
		"""
		Places only single tag
		"""
		xml_node.appendChild(self.xml.createElement(self.subst[node.kind]))
		return xml_node

	separator_emit = break_emit = single_tag
	
	def content_inside(self, node, xml_node):
		"""
		Places raw text inside node without parsing
		"""
		new_node = self.xml.createElement(self.subst[node.kind])
		xml_node.appendChild(new_node)
		new_node.appendChild(self.xml.createTextNode(node.content))
		return xml_node

	code_emit = preformatted_emit = content_inside
			
	def header_emit(self, node, xml_node):
		new_node = self.xml.createElement('h%d'%node.level)
		xml_node.appendChild(new_node)
		new_node.appendChild(self.xml.createTextNode(node.content))
		return new_node

	def link_emit(self, node, xml_node):
		target = node.content
		link = self.xml.createElement('a')
		xml_node.appendChild(link)
		m = self.addr_re.match(target)
		if m:
			if m.group('extern_addr'):
				link.setAttribute('href', target)
				return link
			elif m.group('inter_wiki'):
				raise NotImplementedError
		link.setAttribute('href', target)
		if(not node.children):
			link.appendChild(self.xml.createTextNode(target))
		return link

	def image_emit(self, node, xml_node):
		target = node.content
		img = self.xml.createElement('img')
		xml_node.appendChild(img)
		text = self.get_text(node)
		m = self.addr_re.match(target)
		node.children = []
		# A bit strange logig below - I'll make it better sometime maybe
		if m:
			if m.group('extern_addr'):
				img.setAttribute('src', target)
				if(text): 
					img.setAttribute('alt', text)
				return xml_node
			elif m.group('inter_wiki'):
				raise NotImplementedError
		img.setAttribute('src', target)
		if(text): 
			img.setAttribute('alt', text)
		return xml_node

	def macro_emit(self, node):
		raise NotImplementedError

	def default_emit(self, node, xml_node):
		"""Fallback function for emitting unknown nodes."""
		raise TypeError, "Unknown node: %s" %node.kind

	def emit_children(self, node, xml_node):
		"""Emit all the children of a node."""
		for n in node.children:
			self.emit_node(n, xml_node)

	def emit_node(self, node, xml_node):
		"""Emit a single node."""
		emit = getattr(self, '%s_emit' % node.kind, self.default_emit)
		new_node = emit(node, xml_node)
		self.emit_children(node, new_node)

	def emit(self):
		"""Emit the document represented by self.root DOM tree."""
		self.emit_node(self.root, self.xml.documentElement)

if __name__=="__main__":
	import sys
	impl = dom.getDOMImplementation()
	xml = impl.createDocument(None, 'part', None)
	document = Parser(unicode(sys.stdin.read(), 'utf-8', 'ignore')).parse()
	MinidomEmitter(document, xml.documentElement).emit()
	print xml.toxml()


